package com.naiterui.ehp.ps.sms.factory.yunuo;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import com.naiterui.ehp.ps.sms.enums.HuaweiStatusEnum;
import com.naiterui.ehp.ps.sms.exception.ExceptionCodes;
import com.naiterui.ehp.ps.sms.exception.SmsBusinessException;
import com.naiterui.ehp.ps.sms.factory.yunuo.YunuoConstants.SendSmsResult;
import com.naiterui.ehp.ps.sms.vo.MessageResponseVO;

import lombok.extern.slf4j.Slf4j;

/**
 * @author gaoliangliang
 * @date 2020/12/29 下午6:45
 **/
@Slf4j
public class YunuoSms {

    public static MessageResponseVO singleSend(String phone, String templateId, String[] datas)
        throws SmsBusinessException {

        AtomicInteger index = new AtomicInteger(1);
        Map<String, String> params =
            Arrays.stream(datas).collect(Collectors.toMap(o -> index.getAndAdd(1) + "", data -> data));
        // 发送短信
        SendSmsResult result = YunuoApi.singleSend(phone, templateId, params);
        log.info("[发送短信，雨诺平台]--短信发送完成，手机号电话号码:[{}] 模板ID:[{}] 模板参数:[{}] 第三方平台返回结果:[{}]", phone, templateId, datas,
            result);
        MessageResponseVO messageResponseVO = processApiResult(result);
        return messageResponseVO;
    }

    private static MessageResponseVO processApiResult(SendSmsResult result) throws SmsBusinessException {
        // 处理api请求结果
        if (result == null) {
            log.error("雨诺平台返回结果为空");
            throw new SmsBusinessException(ExceptionCodes.SMS_PLATFORM_RETURN_NULL);
        }
        MessageResponseVO responseVO = new MessageResponseVO();
        if (YunuoConstants.REQUEST_SUCCESS_STR.equals(result.getResult())) {
            responseVO.setStatusCode(String.valueOf(ExceptionCodes.SUCCESS));
            responseVO.setStatusMsg(HuaweiStatusEnum.SMS_SUCCESS.msg());
        } else {
            responseVO.setStatusCode(String.valueOf(ExceptionCodes.SMS_PLATFORM_RETURN_ERROR));
            responseVO.setStatusMsg("雨诺平台短信发送失败");
        }

        return responseVO;
    }

}
